﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using blackhouse.WebNemo.Data;

namespace blackhouse.WebNemo.Business.Translate {
    public class DaTranslate : ITranslate {

        #region Field

        private IDataAccess dataAccess;
        private CultureInfo[] avalibleLanguages;
        private int groupId;
        private int fieldId;
        private int recordId;
        private Dictionary<string, string> translates = new Dictionary<string, string>();

        #endregion

        #region Constructors

        public DaTranslate(IDataAccess data) {
            this.dataAccess = data;
        }

        private DaTranslate(IDataAccess data, int groupId, int fieldId, int recordId) {
            this.dataAccess = data;
            this.groupId = groupId;
            this.fieldId = fieldId;
            this.recordId = recordId;
        }

        #endregion

        #region Methods

        public CultureInfo[] GetAvalibleLanguages() {
            if (avalibleLanguages == null) {
                string[] langCodes = this.dataAccess.GetAvalibleLanguages();
                this.avalibleLanguages = ReadLanguages(langCodes);
            }
            return this.avalibleLanguages;
        }

        private CultureInfo[] ReadLanguages(string[] langCodes) {
            return
                langCodes.Select(lc => CultureInfo.GetCultureInfo(lc)).ToArray();
        }

        public ITranslate GetTranslate(int groupId, int fieldId, int recordId) {
            return new DaTranslate(this.dataAccess, groupId, fieldId, recordId);
        }

        public string Translation(CultureInfo cultureInfo) {
            if (!translates.ContainsKey(cultureInfo.Name))
                translates.Add(cultureInfo.Name, this.dataAccess.GetTranslate(groupId, fieldId, recordId, cultureInfo.Name));
            return translates[cultureInfo.Name];
        }

        public string TranslationOryginal() {
            if (!translates.ContainsKey("oryginal"))
                translates.Add("oryginal", this.dataAccess.GetOryginalTranslate(groupId, fieldId, recordId));
            return translates["oryginal"];
        }

        public void SetTranslation(CultureInfo cultureInfo, string value) {
            if (value == Translation(cultureInfo)) return;
            if (String.IsNullOrEmpty(value) || value == TranslationOryginal())
                this.dataAccess.RemoveTranslate(groupId, fieldId, recordId, cultureInfo.Name);
            else
                this.dataAccess.SetTranslate(groupId, fieldId, recordId, cultureInfo.Name, value, Factory.Instance().GetCurrentUser().UserId);
            translates[cultureInfo.Name] = value;
        }

        #endregion

    }
}
